<template>
  <div class="post-card-list">
    <!-- 遍历帖子列表 -->
    <van-cell-group v-for="post in postList" :key="post.id" class="post-card">
      <!-- 用户信息 -->
      <div class="user-info">
        <van-image
            round
            width="50px"
            height="50px"
            :src="post.avatarUrl"
            class="user-avatar"
            @click="goToUserinfo(post.userId)"
        />
        <div class="user-meta">
          <div class="username-time">
            <span class="username">{{ post.userName }}</span>
            <span class="time">{{ formatTime(post.createTime) }}</span>
            <!-- 添加三个点图标 -->
            <van-icon
                v-if="post.userId === currentUserId"
                name="more-o"
                class="more-icon"
                @click.stop="showActionSheet(post)"
            />
          </div>
          <div class="title" v-if="post.title">{{ post.title }}</div>
        </div>
      </div>

      <!-- 帖子内容 -->
      <div class="post-content">
        <p>{{ post.content }}</p>
        <!-- 图片展示 -->
        <div class="image-container">
          <van-image
              v-for="(img, index) in parseImages(post.images)"
              :key="index"
              width="55%"
              height="auto"
              :src="img"
              @click="previewImage(parseImages(post.images), index)"
              v-if="post.images && parseImages(post.images).length > 0"
              class="post-image"
          />
        </div>
      </div>

      <!-- 互动操作 -->
      <div class="post-actions">
        <div
            class="action-item"
            @click="handleLike(post)"
        >
          <van-icon
              :name="(post.followsIds || []).includes(currentUserId) ? 'like' : 'like-o'"
          />
          <span>{{ post.followsNum }}</span>
        </div>
        <!-- 评论按钮部分 -->
        <div class="action-item" @click="handleComment(post)">
          <van-icon name="comment-o" />
          <span>{{ post.commentNum }}</span>
        </div>
      </div>
    </van-cell-group>
    <!-- 操作菜单 -->
    <van-action-sheet
        v-model:show="showActions"
        :actions="actions"
        @select="onActionSelect"
        cancel-text="取消"
    />
  </div>
</template>

<script setup>
import { ImagePreview, Toast } from 'vant';
import {ref} from "vue";
import {useRouter} from "vue-router";
import myAxios from "../plugins/myAxios.ts";

// 获取当前用户ID（从 localStorage）
const currentUserId = ref(parseInt(localStorage.getItem("userId")) || null);

const router = useRouter();
// 添加ActionSheet和Dialog的引入
import { ActionSheet, Dialog } from 'vant';

// 添加操作相关状态
const showActions = ref(false);
const currentPost = ref(null);

const actions = [
  { name: '删除', key: 'delete' }
];
//判断是否已点赞，followsIds是否是数组
const isLiked = (post) => {
  // 确保 followsIds 是数组
  let followsIds = post.followsIds;

  // 如果 followsIds 是字符串，解析为数组
  if (typeof followsIds === 'string') {
    try {
      followsIds = JSON.parse(followsIds);
    } catch (e) {
      console.error('解析 followsIds 失败:', e);
      followsIds = [];
    }
  }
  // 确保 followsIds 是数组
  followsIds = Array.isArray(followsIds) ? followsIds : [];
  // 判断是否已点赞
  return followsIds.some(id => id === currentUserId.value);
};

// 点赞处理逻辑
const handleLike = async (post) => {
  if (!currentUserId.value) {
    return Toast('请先登录');
  }

  const wasLiked = isLiked(post);

  try {
    const res = await myAxios.post(wasLiked ? '/post/lessLike' : '/post/addLike', {
      postId: post.id,
    });

    if (res?.code === 0) {
      post.followsNum = res.data.followsNum;

      // 确保 followsIds 是数组
      const currentFollowsIds = Array.isArray(post.followsIds) ? post.followsIds : [];

      post.followsIds = wasLiked
          ? currentFollowsIds.filter(id => id !== currentUserId.value)
          : [...currentFollowsIds, currentUserId.value];
      Toast.success(res.data.info);
    } else {
      Toast.fail(res?.message || '操作失败');
    }
  } catch (error) {
    Toast.fail(error.message);
    console.error('点赞请求失败', error);
  }
};
const showActionSheet = (post) => {
  currentPost.value = post;
  showActions.value = true;
};

const onActionSelect = (action) => {
  if (action.key === 'delete') {
    Dialog.confirm({
      title: '确认删除',
      message: '确定要删除这条帖子吗？',
    }).then(() => {
      handleDeletePost(currentPost.value);
    }).catch(() => {});
  }
  showActions.value = false;
};

const emit = defineEmits(['delete-post']);

const goToUserinfo = (userId) => {
  router.push(`/user/show/${userId}`);
};

const handleDeletePost = async (post) => {
  try {
    const res = await myAxios.post('/post/delete', { postId: post.id });
    if (res.code === 0) {
      Toast.success('删除成功');
    }else {
      Toast.fail(res?.message || '删除失败');
    }
    window.location.reload();
  } catch (error) {
    Toast.fail('删除失败');
  }
};

// 解析 images 字段
const parseImages = (images) => {
  try {
    return JSON.parse(images) || [];
  } catch (e) {
    console.error('解析图片失败', e);
    return [];
  }
};

// 时间格式化
const formatTime = (date) => {
  return date; // 直接返回日期字符串，或者可以根据需要格式化
};

// 图片预览
const previewImage = (images, index) => {
  ImagePreview({
    images,
    startPosition: index,
    closeable: true,
  });
};

defineProps({
  postList: {
    type: Array,
    required: true
  }
});

// 在script中添加
const handleComment = (post) => {
  router.push(`/post/comment/${post.id}`); // 使用反引号包裹字符串
};


</script>

<style scoped>
.post-card-list {
  padding: 16px;
}

.post-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 8px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 50px;
  height: 50px;
  margin-right: 12px;
  cursor: pointer;
}

.user-meta {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
}

.username-time {
  display: flex;
  align-items: center;
  gap: 8px; /* 用户名和时间之间的间距 */
  margin-bottom: 4px; /* 与标题的间距 */
}

.username {
  font-weight: bold;
  font-size: 16px;
}

.time {
  font-size: 12px;
  color: #999;
}

.title {
  font-weight: bold;
  font-size: 15px;
  color: #333;
  margin-left: 1px;
  color: black;
}

.post-content {
  padding: 8px;
}

.post-content p {
  margin: 0 0 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

.post-actions {
  display: flex;
  justify-content: space-around; /* 或 space-between 根据需求调整 */
  padding: 10px 0;
}

.action-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  transition: all 0.3s ease;
}
.action-item:active {
  transform: scale(0.95);
}

.van-icon {
  font-size: 18px;
}
.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.post-image {
  flex: 1 1 calc(24% - 2px);
  max-width: calc(24% - 2px);
}

.user-info {
  position: relative; /* 添加定位上下文 */
}

.more-icon {
  position: absolute;
  right: 0;
  top: 0;
  padding: 8px;
  font-size: 18px;
  color: #666;
}

.username-time {
  position: relative;
  padding-right: 30px; /* 给图标留出空间 */
}
</style>
